import time
from typing import Dict, Optional

# 定义订单书类型
BOOK_TYPES = {
    "source": "sourcebook",  # 源订单书
    "copper": "copper_book",  # 铜锤单
    "bronze": "bronze_book",  # 青铜锤单
    "ancient": "ASH_book",  # 远古锤单
    "power_scroll": "PS_book",  # 技能卷单
    "good": "good_book",  # 金锤及以上订单
    "iron_trash": "Irontrashbod",  # 垃圾铁矿单
    "color_trash": "Colortrashbod",  # 垃圾彩矿单
    "trash": "trashbin"  # 垃圾桶
}

def get_required_items() -> Optional[Dict[str, int]]:
    """获取所有需要的物品（订单书和垃圾桶）"""
    items = {}
    
    # 获取源订单书
    Misc.SendMessage("选择要挑选的订单书", 33)
    items["source"] = Target.PromptTarget()
    if not items["source"]:
        return None
        
    # 获取分类用的订单书
    for book_type, message in BOOK_TYPES.items():
        if book_type == "source" or book_type == "trash":
            continue
            
        Misc.SendMessage(f"选择{message}", 33)
        book = Target.PromptTarget()
        if not book:
            return None
        items[book_type] = book
        
    # 获取垃圾桶
    Misc.SendMessage("选择垃圾桶", 33)
    items["trash"] = Target.PromptTarget()
    if not items["trash"]:
        return None
        
    return items

def wait_for_save() -> None:
    """等待世界保存完成"""
    if Journal.Search("The world will save in 10 seconds."):
        save_timer = time.time()
        while not Journal.Search("World save complete."):
            if time.time() - save_timer >= 28:
                break
            Misc.Pause(100)
        Journal.Clear()

def process_bod(bod: int, items: Dict[str, int]) -> None:
    """处理单个订单并移动到对应的书中"""
    Items.WaitForProps(bod, 6000)
    
    # 根据订单属性分类
    if Items.GetPropValue(bod, "Platemail") or Items.GetPropValue(bod, "Plate Helm"):
        # 精良铁矿铠甲单和普通暗铜铠甲单归到铜锤单
        Items.Move(bod, items["copper"])
    elif Items.GetPropValue(bod, "Large Bulk Order"):
        # 大订单直接进垃圾桶
        Items.Move(bod, items["trash"])
    else:
        # 其他铁矿单归入垃圾单
        Items.Move(bod, items["iron_trash"])
        
    Misc.Pause(600)

def process_source_book(items: Dict[str, int]) -> None:
    """处理源订单书中的所有订单"""
    while True:
        wait_for_save()
        
        # 检查源订单书是否还有订单
        Items.WaitForProps(items["source"], 3000)
        if not Items.GetPropValue(items["source"], "Deeds in Book"):
            break
            
        # 打开源订单书
        Items.UseItem(items["source"])
        if not Gumps.WaitForGump(0x54f555df, 15000):
            break
            
        # 导航菜单获取订单
        Gumps.SendAction(0x54f555df, 1)
        if not Gumps.WaitForGump(0x968739db, 15000):
            break
            
        # 选择精良铁矿单
        Gumps.SendAction(0x968739db, 3)
        if not Gumps.WaitForGump(0x968739db, 15000):
            break
            
        Gumps.SendAction(0x968739db, 4)
        if not Gumps.WaitForGump(0x968739db, 15000):
            break
            
        Gumps.SendAction(0x968739db, 13)
        if not Gumps.WaitForGump(0x968739db, 15000):
            break
            
        Gumps.SendAction(0x968739db, 10)
        if not Gumps.WaitForGump(0x968739db, 15000):
            break
            
        Gumps.SendAction(0x968739db, 19)
        if not Gumps.WaitForGump(0x968739db, 15000):
            break
            
        Gumps.SendAction(0x968739db, 0)
        if not Gumps.WaitForGump(0x54f555df, 15000):
            break
            
        Misc.Pause(600)
        
        # 处理背包中的订单
        while True:
            take_timer = time.time()
            Gumps.SendAction(0x54f555df, 5)
            
            # 等待订单出现在背包中
            bod = Items.FindByID(0x2258, 1102, Player.Backpack.Serial)
            if not bod:
                if time.time() - take_timer >= 5:
                    break
                Misc.Pause(600)
                continue
                
            # 处理订单
            process_bod(bod, items)
            
            # 关闭打开的菜单
            while Gumps.CurrentGump() == 0x54f555df:
                Gumps.SendAction(0x54f555df, 0)
                
        # 检查是否处理完当前书
        if not Gumps.CurrentGump() == 0x54f555df:
            break

def do_organize_orders() -> None:
    """整理订单的主函数"""
    Misc.SendMessage("开始整理订单...", 33)
    
    # 获取所需物品
    items = get_required_items()
    if not items:
        Misc.SendMessage("获取物品失败，整理订单终止", 33)
        return
        
    # 处理源订单书
    process_source_book(items)
    Misc.SendMessage("订单整理完成", 33)

if __name__ == "__main__":
    do_organize_orders() 